package com.zcw.rabbitmq.chatroomv4;

import com.rabbitmq.client.Channel;
import com.zcw.rabbitmq.chatroomv2.ChatRoom;

import java.io.IOException;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * 消息发送者
 */
public class Sender {

    private Channel channel;
    private String roomName;
    private String userName;

    BlockingQueue<String> messageQueue = new LinkedBlockingQueue<>();

    public Sender(){

    }

    public Sender(String roomName,String userName){
        this.roomName = roomName;
        this.userName = userName;
    }

    public void insertMessage(String msg){
        try {
            messageQueue.put(msg);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }


    public void sendMessage(){
        // 获取房间
        this.channel = ChatRoom.getChatRoom(this.roomName, this.userName);
        // 发送消息
        try {
            String message = messageQueue.take();
            if (message == null || "".equals(message)){
                System.out.println("不能发送空消息");
                return;
            }
            channel.basicPublish(this.roomName, "", null, message.getBytes("UTF-8"));
            System.out.println("消息：'" + message + "'发送成功！");
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

    }





}
